//手写Promise

const SUCCESS = 'rejected';
const FAIL = 'fulfilled';
const PENDDING = 'pendding';
class Promise {
  constructor(excutor) {
    this.status = PENDDING; //等待状态
    this.value = undefined;
    this.reason = undefined;

    this.onResolvedCallbacks = []; //所有成功
    this.onRejectedCallbacks = []; //所有失败
    this.onErrorCallbacks = [];// 所有的异常
    let resolve = (value) => {
      if (this.status === PENDDING) {
        this.status = SUCCESS;
        this.value = value;
        this.onResolvedCallbacks.forEach((fn=>fn()))
      }
    };
    let reject = (reason) => {
      if (this.status === PENDDING) {
        this.status = FAIL;
        this.reason = reason;
        this.onRejectedCallbacks.forEach((fn=>fn()))
      }
    };
    //马上执行
    try {
      excutor(resolve, reject)
    } catch (error) {
      console.log(error);
      console.log('进入ERROR catch');
      //有问题
      this.onErrorCallbacks.forEach(fn=>fn('wo 拿到 try catch '));
    }
  }
  then(onFulfilled, onRejected) {
    if (this.status === SUCCESS) {
      onFulfilled(this.value);
    }
    if (this.status === FAIL) {
      onRejected(this.reason);
    }
    //订阅发布
    if (this.status === PENDDING) {
     this.onResolvedCallbacks.push(()=>{
      onFulfilled(this.value);
     })
     this.onRejectedCallbacks.push(()=>{
      onRejected(this.reason);
     })
    }
    return this;
  }
  catch(onError){
    this.onErrorCallbacks.push(onError);
  }
}
module.exports = Promise;